<template>
    <div class="app-container">
      <el-row style="width: 100%;height: 100%;margin: 0;" :gutter="10">
        <!--区域数据-->
        <el-col :span="4" style="height: 100%;padding-left: 0;">
          <div style="background-color: #FFFFFF;height: 100%;padding: 10px;">
            <el-input placeholder="输入关键字进行过滤" clearable size="mini" suffix-icon="el-icon-search"
                      style="width: 100%;" v-model="filterText"/>
            <el-tree
                :data="sheetsTreeList"
                :props="defaultProps"
                :expand-on-click-node="false"
                :filter-node-method="filterNode"
                ref="tree"
                node-key="code"
                default-expand-all
                highlight-current
                v-loading="treeLoading"
                style="height: 97%;overflow-y: auto;"
                @node-click="handleNodeClick"
            />
          </div>
        </el-col>

        <el-col :span="20" style="height: 100%;background-color: #FFFFFF;">
          <div style="width: 100%;margin: 10px 5px 10px 0;">
            <el-row class="line-bottom" v-show="showSearch">
              <el-col class="form_col">


                <el-form :model="queryParams" ref="queryForm" :size="formItemSize" v-show="showSearch"
                         :label-width="labelWidth" v-if="refresh" >
                  <div id="searchFilter" :gutter="10" style="display: flex; flex-wrap: wrap">


                    <el-form-item label="用户名称" prop="userName">
                      <el-input :size="formItemSize"
                                v-model="queryParams.userName"
                                placeholder="请输入用户名称"
                                clearable
                                style="width: 100%;"/>
                    </el-form-item>
                    <el-form-item label="用户编号" prop="userId">
                      <el-input :size="formItemSize"
                                v-model="queryParams.userId"
                                placeholder="请输入用户编号"
                                clearable
                                @keyup.enter.native="handleQuery"
                      />
                    </el-form-item>
                    <el-form-item label="设备编号" prop="terminalId">
                      <el-input :size="formItemSize"
                                v-model="queryParams.terminalId"
                                placeholder="请输入设备编号"
                                clearable
                                @keyup.enter.native="handleQuery"
                      />
                    </el-form-item>
                    <el-form-item label="用户通讯地址" prop="userAddress">
                      <el-input :size="formItemSize"
                                v-model="queryParams.userAddress"
                                placeholder="输入通讯地址"
                                clearable
                      />
                    </el-form-item>

                    <el-form-item label="未抄回类型">
                      <el-select placeholder="选择数据类型" v-model="dataModel" @change="disabledDate">
                        <el-option label="实时数据" value="实时数据" ></el-option>
                        <el-option label="历史数据" value="历史数据" ></el-option>
                      </el-select>
                  </el-form-item>

                    <el-form-item label="日期">
                      <div class="block">
                        <el-date-picker
                          v-model="dateRangeReadDate"
                          type="daterange"
                          value-format="yyyy-MM-dd"
                          range-separator="至"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期">
                        </el-date-picker>
                      </div>
                    </el-form-item>

                    <el-form-item>
                    </el-form-item>




                  </div>
                </el-form>
              </el-col>
              <el-col class="form_query">
                <el-button v-show="collapseAble" type="text" @click="shiftCollapseAble" class="text">
                <span>
                  {{ fold ? '收起筛选' : '更多筛选' }}
                </span>
                </el-button>
                <el-button type="primary" @click="handleQuery" size="mini">查询</el-button>
                <el-button @click="resetQuery" size="mini">重置</el-button>
              </el-col>
            </el-row>

            <el-row :gutter="10" class="mb8">
              <RightDropdown :columns="columns" :showSearch.sync="showSearch" @queryTable="getList_2" @export="handleExport"
                             :hasPermiExport="['datastatistics:realtimegatherdataxb:export']"></RightDropdown>
            </el-row>

            <el-table ref="table" v-loading="loading" :data="dataList" border size="mini"
                      :default-sort="defaultSort" @sort-change="handleSorterChange" :height="getAvailableHeight" >
              <el-table-column type="index" label="#" width="40" align="center"/>
              <el-table-column label="用户名称" align="center" prop="userName" v-if="columns[0].visible"
                               sortable="custom" :sort-orders="['ascending','descending']" :show-overflow-tooltip="true"/>
              <el-table-column label="用户编号" align="center" prop="userId" v-if="columns[1].visible"
                               sortable="custom" :sort-orders="['ascending','descending']" :show-overflow-tooltip="true"/>
              <el-table-column label="门牌号" align="center" prop="installAddress" v-if="columns[2].visible"
                               sortable="custom" :sort-orders="['ascending','descending']" :show-overflow-tooltip="true"/>
              <el-table-column label="设备编号" align="center" prop="terminalId" v-if="columns[3].visible"
                               sortable="custom" :sort-orders="['ascending','descending']" :show-overflow-tooltip="true"
                               width="140"/>
              <el-table-column label="用户通讯地址" align="center" prop="userAddress" v-if="columns[4].visible"
                               sortable="custom" :sort-orders="['ascending','descending']" :show-overflow-tooltip="true"
                               width="150"/>
              <el-table-column label="水表读数(m³)" align="center" prop="totalFlow" v-if="columns[5].visible"
                               sortable="custom" :sort-orders="['ascending','descending']" :show-overflow-tooltip="true"/>
              <el-table-column label="终端电压(V)" align="center" prop="terminalVol" v-if="columns[6].visible"
                               sortable="custom" :sort-orders="['ascending','descending']" :show-overflow-tooltip="true"/>
              <el-table-column label="阀门状态" align="center" prop="valveState" v-if="columns[7].visible"
                               sortable="custom" :sort-orders="['ascending','descending']" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <span v-if="scope.row.valveState === 1">开</span>
                  <span v-if="scope.row.valveState === 0">关</span>
                </template>
              </el-table-column>
              <el-table-column label="抄表时间" align="center" prop="readDate" v-if="columns[7].visible"
                               sortable="custom" :sort-orders="['ascending','descending']" :show-overflow-tooltip="true"
                               width="180">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.readDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
                </template>
              </el-table-column>
            </el-table>
            <pagination :total="total"
                        :page.sync="queryParams.pageNum"
                        :limit.sync="queryParams.pageSize"
                        @pagination="getList_2"
            />
          </div>
        </el-col>
      </el-row>
    </div>
  </template>

  <script>
  import {listRealtimegatherdataXbView} from "@/api/dataquery/metered/realtimegatherdataXbView";
  import {listMeterSheetsTree} from "@/api/basedata/meterSheets";
  import {listData,didNotCopyBackToday,historyNotCopyBack} from "@/api/dataquery/metered/norealtimedataxb";
  import moment from "moment";

  export default {
    name: "Realtimegatherdataxb",
    dicts: ['belong_department'],
    data() {
      return {
        showCmd: true,
        refresh: true,
        dataModel:'',
        screenHeight: null,
        formItemSize: 'mini',
        collapseAble: false,
        fold: false,
        maxShow: 8,
        labelWidth: '100px',
        // 列信息
        columns: [
          {key: 0, label: `用户名称`, visible: true},
          {key: 1, label: `用户编号`, visible: true},
          {key: 2, label: `门牌号`, visible: true},
          {key: 3, label: `设备编号`, visible: true},
          {key: 4, label: `用户通讯地址`, visible: true},
          {key: 5, label: `水表读数`, visible: true},
          {key: 6, label: `终端电压`, visible: true},
          {key: 7, label: `阀门状态`, visible: true},
          {key: 8, label: `抄表时间`, visible: true},
        ],
        // ruleForm: {
        //   date1: '',
        //   date2: ''
        // },
        defaultProps: {
          children: "children",
          label: "name"
        },
        filterText: '',
        // 默认排序
        defaultSort: {prop: 'readDate', order: 'descending'},
        // 区域树选项
        sheetsTreeList: [],
        // 遮罩层
        loading: true,
        treeLoading: true,
        TerminalIDs: [],
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 实时数据采集（小）表格数据
        dataList: [],
        // 时间范围
        dateRangeReadDate: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 20,
          sheetsCode: null,
          userName: null,
          userId: null,
          terminalId: null,
          userAddress: null,
          communicateAddress: null,
          params: {
            beginReadDate:'',
            endReadDate:''
          },
        },
      };
    },
    created() {
      // this.screenHeight = document.body.clientHeight
      // console.log(this.screenHeight);
      // 因为搜索栏多出两个条件所以，将表格的高度进行了一个调整，以便操作展示
      this.screenHeight = 920
    },
    computed: {
      getAvailableHeight() {
        return this.screenHeight - (this.showSearch ? 230 : 185)
      }
    },
    mounted() {
      this.dataModel='实时数据';
      this.getTreeList();
      this.getList_2();
      // 通过最大显示个数控制展开/折叠
      if (this.maxShow > 0) {
        this.minShowControl()
      }
    },
    watch: {
      // 根据名称筛选区域树
      filterText(val) {
        this.$refs.tree.filter(val);
      },
      // 绑定时间
      dateRangeReadDate(val) {
      if (val != null && val.length) {
        this.queryParams.params.beginReadDate = val[0];
        this.queryParams.params.endReadDate = val[1];
      } else {
        this.queryParams.params.beginReadDate = "";
        this.queryParams.params.endReadDate = "";
      }
    },
    },
    methods: {
      /** 排序触发事件 */
      handleSorterChange({column, prop, order}) {
        this.queryParams.orderByColumn = prop
        this.queryParams.isAsc = order
        this.getList()
      },
      /** 检查设置排序字段 */
      checkSortColumn() {
        if (!this.queryParams.orderByColumn) {
          this.queryParams.orderByColumn = this.defaultSort.prop
          this.queryParams.isAsc = this.defaultSort.order
        }
      },
      // 初始化表格 解决表格固定操作列的问题
      init() {
        // 调用接口获取到数据后
        let _self = this
        this.$nextTick(() => {
          window.setTimeout(() => {
            _self.$refs.table.doLayout()
          }, 100)
        })
      },
      // 展开折叠按钮
      shiftCollapseAble() {
        this.fold = !this.fold
        this.minShowControl()
      },
      // 通过maxShow控制元素显示/折叠
      minShowControl() {
        const group = window.document.querySelectorAll(`#searchFilter .el-form-item.el-form-item--${this.formItemSize}`)
        const len = group?.length ? group?.length : 0
        if (this.maxShow < len) {
          group.forEach((item, index) => {
            if (index > this.maxShow - 1 && index < len) {
              item.hidden = !this.fold
            }
          })
          this.collapseAble = true
        } else {
          this.collapseAble = false
        }
      },
      // 筛选节点
      filterNode(value, data) {
        if (!value) return true;
        return data.name.indexOf(value) !== -1;
      },
      /** 查询区域树 */
      getTreeList() {
        this.treeLoading = true;
        listMeterSheetsTree({}).then(response => {
          this.sheetsTreeList = response;
          this.treeLoading = false;
        });
      },

      //根据类型(实时数据/历史数据)来查询不同的未抄回数据
      getList_2(){
        if(this.dataModel==='实时数据' || this.dataModel==null || this.dataModel == ''){
          didNotCopyBackToday(this.queryParams).then(response => {
            this.dataList = response.rows;
            this.total = response.total;
            this.init()
            this.loading = false;
          });
        }
        if(this.dataModel==='历史数据'){
          //查询历史数据需要时间
          if(this.queryParams.params.beginReadDate==null||this.queryParams.params.beginReadDate==''||
          this.queryParams.params.endReadDate==null||this.queryParams.params.endReadDate==''){
            this.$modal.msgWarning("查询历史数据，时间不能为空!")
          }else{
            console.log(this.queryParams);
          historyNotCopyBack(this.queryParams).then(response => {
            this.dataList = response.rows;
            this.total = response.total;
            this.init()
            this.loading = false;
          });
          }
        }
      },
      handleNodeClick(data){
        this.handleQuery()
      },
      /** 搜索按钮操作 */
      handleQuery() {
        // if(queryParams.data1!=null&&queryParams.date2!=null){
          this.queryParams.pageNum = 1;
          this.getList_2();
        // }

      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 导出按钮操作 */
      handleExport() {
        if(this.dataModel==='实时数据'){
          this.download('basedata/notcopiedback/export', {
          ...this.queryParams
        }, `实时未抄表数据.xlsx`)
        }else{
          this.download('basedata/notcopiedback/export2', {
          ...this.queryParams
        }, `历史未抄表数据.xlsx`)
        }
      },
      /**进行日期的切换，当变为实时数据时，清空日期，当变为历史数据时，给默认值 */
      disabledDate(){
        if(this.dataModel==='实时数据'){
          this.dateRangeReadDate=[];
          this.queryParams.params.beginReadDate = "";
          this.queryParams.params.endReadDate = "";
          this.queryParams.date1=null
        }else{
          this.dateRangeReadDate = [moment().subtract(1, 'day').format('YYYY-MM-DD'), moment().subtract(1, 'day').format('YYYY-MM-DD')];
            this.queryParams.params = {
              beginReadDate: moment().subtract(1, 'day').format('YYYY-MM-DD'),
              endReadDate: moment().subtract(1, 'day').format('YYYY-MM-DD')
            };
        }
        //强制刷新渲染页面
        this.refresh = false
            this.$nextTick(() => {
                this.refresh = true
            })
      },

    }
  };
  </script>
